#![allow(dead_code)]
use crossbeam::channel::{unbounded,Sender,Receiver};
use std::any::Any;

#[derive(Clone)]
pub struct ThreadChanel{
    sender:Sender<Box<dyn Any + Send + 'static>>,
    receiver:Receiver<Box<dyn Any + Send + 'static>>
}
impl ThreadChanel
{
    pub fn new()->Self{
        let (sender,receiver) = unbounded();
        Self{sender,receiver}
    }

    pub fn send(&self, m:impl Send+'static) -> Result<(), String> {
        self.sender.send(Box::new(m)).map_err(|e|{e.to_string()})
    }
    pub fn send_timeout<M:Send+'static>(&self, m:M, timeout:std::time::Duration) -> Result<(), String> {
        self.sender.send_timeout(Box::new(m),timeout).map_err(|e|e.to_string())
    }
    pub fn recv<M:'static>(&self)->Result<M,String>{
        let res = self.receiver.recv().map_err(|e|e.to_string())?;
        match res.downcast::<M>() {
            Ok(o)=> Ok(*o),
            Err(_e)=>Err("type error".to_string())
        }
    }
    pub fn recv_timeout<M:'static>(&self,timeout:std::time::Duration)->Result<M,String>{
        let res = self.receiver.recv_timeout(timeout).map_err(|e|e.to_string())?;
        match res.downcast::<M>() {
            Ok(o)=> Ok(*o),
            Err(_e)=>Err("type error".to_string())
        }
    }
}